//
//  RegisterViewController.m
//  Arts1
//
//  Created by 孤星晨宇 on 15/9/14.
//  Copyright (c) 2015年 Arts1. All rights reserved.
//

#import "RegisterViewController.h"
#import "AllHeader.h"
#import "NSString+MD5.h"
#import "RegisterInfoController.h"

//发送手机验证码
#define kSendPhoneCode @"http://arts1.dlab.com.cn/app/sendphonecode"

//验证手机验证码是否正确
#define kVerifyPhoneCode @"http://arts1.dlab.com.cn/app/verifyphonecode"

//用户注册
#define kRegister @"http://arts1.dlab.com.cn/app/reg"


@interface RegisterViewController ()

// 重发验证码的剩余时间
@property (nonatomic, assign) NSInteger second;

//
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = kCustomColor(245, 245, 245, 1);
    _second = 60;
    // Do any additional setup after loading the view from its nib.
    [self modifySubview];
    [self backToHomeView];
}

// 注册完成设置，返回主页面
- (void)backToHomeView
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(finishRegister) name:@"RegiserAndSetting" object:nil];
    
}
- (void)finishRegister{
    [self.navigationController popViewControllerAnimated:NO];
}


// 开启NStimer
- (void)addTimer{
    _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(changeTime) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
}

// 关闭NStimer
- (void)removeTimer{
    [_timer invalidate];
}

// 递减重新发送验证码剩余时间
- (void)changeTime{
    _second --;
   [_identifyBTN setTitle:[NSString stringWithFormat:@"(%ld 秒)重发",(long)_second] forState:(UIControlStateSelected)];
    if (_second == 0) {
        _identifyBTN.selected = NO;
        _identifyBTN.userInteractionEnabled = YES;
        [self removeTimer];
        _second = 60;
    }
}


// 修饰视图
- (void)modifySubview{
//  注册按钮
    _registBTN.layer.cornerRadius = 4;
    _registBTN.layer.masksToBounds = YES;

    // 验证码按钮
    _identifyBTN.layer.cornerRadius = 4;
    _identifyBTN.layer.masksToBounds = YES;
    
    // 视图加阴影
    [UIView viewWideForShadowColor:_topview];
    [UIView viewShadowColor:_whiteview];
    
    // 白色视图设置圆角
    _whiteview.layer.cornerRadius = 5;
    
}




// 返回
- (IBAction)back:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


// 下一步
- (IBAction)registerUser:(id)sender
{
//    RegisterInfoController *registerInfo = [[RegisterInfoController alloc] init];
//    [self.navigationController presentViewController:registerInfo animated:YES completion:^{
//        
//    }];
    [self registerInfo];
}

//判断注册信息
- (void)registerInfo
{
    if (_pNumber.text.length == 0 || _identify.text.length == 0 || _password.text.length == 0 || _rpassword.text.length == 0)
    {
        [MBProgressHUD show:@"输入信息不完整" icon:nil view:self.view];
    }
    else
    {
        if (_password.text.length < 6)
        {
            [MBProgressHUD show:@"密码不能少于6位" icon:nil view:self.view];
        }
        else
        {
            [self requestVerifyPhoneCode];
        }
    }
}



// 判断注册是否成功
- (void)requestVerifyPhoneCode{
    
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    //MD5加密
    NSString *pwdResult = [NSString MD5WithString:_password.text];
    NSString *rpwdResult = [NSString MD5WithString:_rpassword.text];
    
    NSDictionary *pardic = @{@"phone":_pNumber.text,@"password":pwdResult,@"rpassword":rpwdResult,@"phonecode":_identify.text};
    
    [manage POST:kRegister parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
         // 请求成功的时候调用这个block
        NSDictionary * sender = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers) error:nil];
                
        NSLog(@"%@-----------",sender);
        
         int index = [sender[@"status"] intValue];
         NSString *statusStr = nil;
         switch (index)
         {
             case 1:
             {
                 statusStr = @"注册成功";
                 
                 [[NSUserDefaults standardUserDefaults] setObject:sender forKey:@"dataForKeyAndUid"];
                 RegisterInfoController *registerInfo = [[RegisterInfoController alloc] init];
                 [self.navigationController presentViewController:registerInfo animated:YES completion:^{
                 }];
                 
             }
                 break;
             case 0:
                 statusStr = @"注册失败";
                 break;
             case -1:
                 statusStr = @"手机号码不符合规范";
                 break;
             case -2:
                 statusStr = @"验证码错误";
                 break;
             case -3:
                 statusStr = @"输错5次,该手机号不能注册";
                 break;
             case -4:
                 statusStr = @"验证码不正确";
                 break;
             case -5:
                 statusStr = @"输入信息不正确";
                 break;
             case -6:
                 statusStr = @"两次输入的密码不相同";
                 break;
             case -7:
                 statusStr = @"密码不能少于6位字符";
                 break;
             case -8:
                 statusStr = @"该手机号已被注册";
                 break;
                 
             default:
                 break;
         }
         
         [MBProgressHUD show:statusStr icon:nil view:self.view];
     }
    failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
         // 请求失败的时候调用调用这个block
         [MBProgressHUD show:@"当前网络不可用" icon:nil view:self.view];
    }];
    
}

// 发送验证码
- (IBAction)senIdidentifyingcode:(id)sender
{
    //  验证码按钮
    UIButton *codeBTN = (UIButton *)sender;
    codeBTN.selected = !codeBTN.isSelected;
    
    if (codeBTN.selected) {
        // 被点击之后，更换显示文字
        [codeBTN setTitle:[NSString stringWithFormat:@"(%ld 秒)重发",(long)_second] forState:(UIControlStateSelected)];
         [self addTimer];
         codeBTN.userInteractionEnabled = NO;
         [self requestSendPhoneCode];
    } else {
        if (_second == 0) {
          codeBTN.selected = !codeBTN.selected;
          codeBTN.userInteractionEnabled = YES;
         [self removeTimer];
        }
    }
}

// 验证码请求
- (void)requestSendPhoneCode{
    
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    NSDictionary *pardic = nil;
    if ( _pNumber.text.length < 11) {
        [MBProgressHUD show:@"请重新输入电话号码" icon:nil view:self.view];
    } else {
        pardic = @{@"phone":_pNumber.text};
    }
    
    [manage POST:kSendPhoneCode parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSString * str = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             
             // 请求成功的时候调用这个block
             NSLog(@"验证码请求--%@", str);
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
}

- (IBAction)service:(id)sender {
 NSLog(@"服务与条款");
}

// 触摸空白区域收回键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
